#!/usr/bin/env python

"""

    IRC Client using python-irclib,
    some code taken from python-irclib.

"""

from irclib import SimpleIRCClient
from irclib import nm_to_n
from irclib import ServerConnectionError
from smsutil import smsutil
from network import SocialNetwork
from ewsmail import ewsmail
import sys, irclib, string

irclib.DEBUG = False

class irc(SimpleIRCClient):
    
    def __init__(self, server, port, nickname, realname, channel, trusted):
        SimpleIRCClient.__init__(self)
        self._server = server
        self._port = port
        self._nickname = nickname
        self._realname = realname
        self._channel = channel
        self._trusted = trusted
        self._reconnection_interval = 60
        for i in ["disconnect", "welcome", "pubmsg"]:
            self.connection.add_global_handler(i, getattr(self, "_on_" + i), -10)
    
    def _check_connection(self):
        if not self.connection.is_connected():
            self.connection.execute_delayed(self.reconnection_interval,
                                            self._check_connection)
            self._connect()
            
    def _connect(self):
        passwd = None
        try:
            self.connect(self._server,
                         self._port,
                         self._nickname,
                         passwd,
                         self._realname)
        except ServerConnectionError:
            pass
        
    def _on_disconnect(self, c, e):
        self.connection.execute_delayed(self.reconnection_interval,
                                        self._check_connection)

    def _on_welcome(self, connection, event):
        self.connection.join(self._channel)

    def _on_pubmsg(self, c, e):
        disaster =  e.arguments()[0].split(',')
        sender = nm_to_n(e.source())
        if sender == self._trusted:
            mag = disaster[0].split('Info Gempa')[1]
            tanggal = disaster[1]
            lok = disaster[2] + disaster[3]
            kedlmn = disaster[4]
            
            smsmsg = "Gempa\n" +\
                     tanggal + "\n" +\
                     mag + "\n" +\
                     lok + "\n" +\
                     kedlmn
            
            #Send SMS
            sms = smsutil()
            sms.send(smsmsg)
            
            #Send Email
            mailmessage = ewsmail()
            mailmessage.send(smsmsg)
            
            #Send Twitter
            a = SocialNetwork()
            a.UpdateStatus(smsmsg)

    def die(self, msg="Quit"):
        self.connection.disconnect(msg)
        sys.exit(0)
    
    def disconnect(self, msg="Loss connection"):
        self.connection.disconnect(msg)
        
    def get_version(self):
        return "pyews"
    
    def on_ctcp(self, c, e):
        if e.arguments()[0] == "VERSION":
            c.ctcp_reply(nm_to_n(e.source()),
                         "VERSION " + self.get_version())
        elif e.arguments()[0] == "PING":
            if len(e.arguments()) > 1:
                c.ctcp_reply(nm_to_n(e.source()),
                             "PING" + e.arguments()[1])
        elif e.arguments()[0] == "DCC" and e.arguments()[1].split(" ", 1)[0] == "CHAT":
            self.on_dccchat(c, e)
    
    def on_dccchat(self, c, e):
        pass
        
    def start(self):
        self._connect()
        SimpleIRCClient.start(self)



